from typing import *

def fourSum(nums: List[int], target: int) -> List[List[int]]:
    nums.sort()
    ans = []
    num_len = len(nums)
    for i in range(num_len):
        if i > 0 and nums[i] == nums[i-1]: continue

        for j in range(i+1, num_len):
            if j > i+1 and nums[j] == nums[j-1]: continue

            l, r = j + 1, num_len - 1
            while l < r:
                if l > j + 1 and nums[l] == nums[l-1]:
                    l += 1
                    continue
                if r < num_len-1 and nums[r] == nums[r+1]:
                    r -= 1
                    continue
                t = nums[i] + nums[j] + nums[l] + nums[r]
                if t == target:
                    ans.append([nums[i], nums[j], nums[l], nums[r]])
                    l += 1
                    r -= 1
                elif t < target:
                    l += 1
                else:
                    r -= 1
    return ans


print("#18. 四数之和\n")

nums = [1,0,-1,0,-2,2]
nums = [1,-2,-5,-4,-3,3,3,5]
target = -11
print(f'ans {fourSum(nums, target)}\n')